<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>音频可视化</title>
    <style>
        canvas {
            display: block;
            margin: 0 auto;
            background-color: #000;
        }
    </style>
</head>
<body>
<button id="startButton">开始可视化</button>
<audio id="audio" controls>
    <source src="test.mp3" type="audio/mpeg">
</audio>
<canvas id="canvas"></canvas>

<script>
    window.onload = function() {
        var audioContext;

        document.getElementById('startButton').addEventListener('click', function() {
            try {
                window.AudioContext = window.AudioContext||window.webkitAudioContext;
                audioContext = new AudioContext();

                var audio = document.getElementById('audio');
                var canvas = document.getElementById('canvas');
                var ctx = canvas.getContext('2d');
                var source = audioContext.createMediaElementSource(audio);
                var analyser = audioContext.createAnalyser();

                canvas.width = window.innerWidth;
                canvas.height = window.innerHeight;

                source.connect(analyser);
                analyser.connect(audioContext.destination);

                analyser.fftSize = 256;
                var bufferLength = analyser.frequencyBinCount;
                var dataArray = new Uint8Array(bufferLength);

                var barWidth = (canvas.width / bufferLength) * 2.5;
                var barHeight;
                var x = 0;

                function renderFrame() {
                    requestAnimationFrame(renderFrame);

                    x = 0;

                    analyser.getByteFrequencyData(dataArray);
                    ctx.fillStyle = '#000';
                    ctx.fillRect(0, 0, canvas.width, canvas.height);

                    for (var i = 0; i < bufferLength; i++) {
                        barHeight = dataArray[i];

                        ctx.fillStyle = 'rgb(' + (barHeight+100) + ',50,50)';
                        ctx.fillRect(x, canvas.height-barHeight/2, barWidth, barHeight/2);

                        x += barWidth + 1;
                    }
                }

                audio.play().then(function() {
                    renderFrame();
                    document.getElementById('startButton').disabled = true;
                }).catch(function(error) {
                    console.log(error);
                });

            } catch(e) {
                alert('Web Audio API is not supported in this browser');
            }
        });
    };
</script>
</body>
</html>
